﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SQLRunner
{
    public partial class Form1 : Form
    {
        string connectionString = "Data Source=rose.arvixe.com;Initial Catalog=aaaaTestOData;Persist Security Info=True;User ID=jbookex;Password=)ok(ij*u;MultipleActiveResultSets=True";
        string file = "LastCommand.txt";
        Exception error = null;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                button1.Enabled = false;
                RunCommand();
                button1.Enabled = true;

                if(error != null)
                    MessageBox.Show(error.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private async void RunCommand()
        {
            //GetData
            string query = richTextBox1.SelectedText.Trim();
            query = (query.Length == 0) ? richTextBox1.Text : query;
            if (string.IsNullOrEmpty(query)) return;

            //BindData
            var dataTable = await ExecuteQueryAsync(connectionString, query);
            dataGridView1.DataSource = null;
            dataGridView1.DataSource = dataTable;

            File.WriteAllText(file, richTextBox1.Text);
        }

        private Task<DataTable> ExecuteQueryAsync(string connectionString, string query)
        {
            return Task.Run<DataTable>(() => ExecuteQuery(connectionString, query));
        }

        public DataTable ExecuteQuery(string connectionString, string sqlString)
        {
            DataTable dt = new DataTable("Table1"); //The Table name MUST be set in order to pass this over WCF

            using (IDbConnection con = new SqlConnection(connectionString))
            {
                using (IDbCommand cmd = new SqlCommand(sqlString, (SqlConnection)con))
                {
                    cmd.CommandTimeout = 0;
                    try
                    {
                        using (SqlDataAdapter adapter = new SqlDataAdapter())
                        {
                            adapter.SelectCommand = (SqlCommand)cmd;
                            adapter.Fill(dt);
                        }
                    }
                    catch (Exception ex)
                    {
                        error = ex;
                        return null;
                    }
                }
            }

            return dt;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData != Keys.F5)
            {
                return base.ProcessCmdKey(ref msg, keyData);
            }

            button1.PerformClick();

            return true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                richTextBox1.Text = File.ReadAllText(file);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}
